﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows.Forms;
using API;
using API.StoreWebService;
using DB;
using mshtml;

namespace ProductManage
{
    public partial class FormPinterest : Form
    {
        public FormPinterest()
        {
            InitializeComponent();
            webBrowser2.Url = new Uri("http://www.pinterest.com/lovebling92/followers/");
        }

        #region autoPin
        private void AutoPin()
        {
            IHTMLWindow2 win = (IHTMLWindow2)webBrowser1.Document.Window.DomWindow;
              
            foreach (IHTMLElement element in win.document.all)
            {
                if (element.className == "rounded Button repinSmall pinIt primary Module btn")
                {
                    element.click();
                    return;
                }
            }
        }

        private void LoadNewPinPage(string urlPage,string urlPic,string strdescription)
        {
            this.webBrowser1.Url = new Uri("http://www.pinterest.com/pin/create/button/?url=" + urlPage + "&media="+urlPic + "&description="+ strdescription);
            
        }

        private catalogProductEntity[] _onlineListProucts;
        private int iOnlineListProucts = 0;
        Timer timerLoadNewPinPage = new Timer();
        Timer timerAutoPin = new Timer();
        private string strPinIndexKey ;
        private string GetPinIndexKey()
        {
            if (string.IsNullOrEmpty(strPinIndexKey))
            {
                var ips = Dns.GetHostAddresses(Environment.MachineName);
                strPinIndexKey = "PinIndex_" + ips[0];
            }
            return strPinIndexKey;
        }
        private int GetPinIndex()
        {
            int index = 0;
            var PinIndex = GeneralParameterDb.DbMysql.GetGeneralParameter(GetPinIndexKey());
            if (PinIndex != null)
            {
                index = Convert.ToInt32(PinIndex.Value);
            }
            else
            {
                GeneralParameterDb.DbMysql.Insert(new GeneralParameter() { ID = GetPinIndexKey(), Value = "0" });
            }
            return index;
        }
        private void buttonStartPin_Click(object sender, EventArgs e)
        {
            _onlineListProucts = StoreApi.Api.GetOnlineProductList();
            this.iOnlineListProucts = GetPinIndex();

            timerLoadNewPinPage.Interval = 1000;
            timerLoadNewPinPage.Tick += timerLoadNewPinPage_Tick;
            timerLoadNewPinPage.Start();
            timerAutoPin.Interval = 10000;
            timerAutoPin.Tick += timerAutoPin_Tick;
        }
        void timerLoadNewPinPage_Tick(object sender, EventArgs e)
        {
            timerLoadNewPinPage.Stop();
            try
            {
                if (iOnlineListProucts >= _onlineListProucts.Count()) iOnlineListProucts = 0;
                catalogProductEntity catalogProduct = _onlineListProucts[iOnlineListProucts++];
                var product = StoreApi.Api.GetProductInfo(catalogProduct, null);
                var imageurl = StoreApi.Api.GetProductImageUrls(product.sku)[0];
                LoadNewPinPage("http://www.maibey.com/" + product.url_path, imageurl, catalogProduct.name);
            }
            catch (Exception)
            {
            }
            timerAutoPin.Start();
        }
        void timerAutoPin_Tick(object sender, EventArgs e)
        {
            timerAutoPin.Stop();
            try
            {
                AutoPin();
                GeneralParameterDb.DbMysql.Update(new GeneralParameter() { ID = GetPinIndexKey(), Value = this.iOnlineListProucts.ToString() });
            }
            catch (Exception)
            {
            }
            timerLoadNewPinPage.Start();
        }
        #endregion

        #region autoFollow        
        Timer timerAutoFollow = new Timer();
        private void buttonStartFollow_Click(object sender, EventArgs e)
        {
            webBrowser2.Url = new Uri("http://www.pinterest.com/lovebling92/followers/");
            timerAutoFollow.Interval = 10000;
            timerAutoFollow.Tick += timerAutoFollow_Tick;
            timerAutoFollow.Start();
        }

        void timerAutoFollow_Tick(object sender, EventArgs e)
        {
            timerAutoFollow.Stop();
            if (!AutoFollow())
            {
                if (ListFollowersEnd)
                    if (!AutoNextUsersFollowerPage())
                    {
                        webBrowser2.Url = new Uri("http://www.pinterest.com/lovebling92/followers/");
                    }
            }
            timerAutoFollow.Start();
        }

        private List<string> PreListFollowers = new List<string>();
        private List<string> ListAllFollowers = new List<string>();
        private int iListAllFollowers = 0;
        private bool ListFollowersEnd;
        private int noFollower = 0;
        private bool AutoFollow()
        {
            int iHaveFollowed = 0;
            IHTMLWindow2 win = (IHTMLWindow2)webBrowser2.Document.Window.DomWindow;


            List<string> listFollowers = new List<string>(); 
            foreach (IHTMLElement element in win.document.all)
            {
                if (element.className == "UserBase ajax User Module gridItem")
                {
                    try
                    {
                        var strFollowers = element.innerHTML.Substring(element.innerHTML.IndexOf("Pins") + 4, element.innerHTML.IndexOf("Followers") - element.innerHTML.IndexOf("Pins") - 4);
                        int iFollowers = Convert.ToInt32(strFollowers.Replace(" ", "").Replace("\n", "").Replace("•", "").Replace(",", ""));
                        var strUser = element.outerHTML.Substring(element.outerHTML.IndexOf("<a class=\"userWrapper\" href=\"") + 29, element.outerHTML.IndexOf("\" data-element-type=\"64\">") - element.outerHTML.IndexOf("<a class=\"userWrapper\" href=\"") - 29);
                        listFollowers.Add(strUser);
                        if (iFollowers > 100)
                        {
                            foreach (IHTMLElement element1 in element.all)
                            {
                                if (element1.className == "UserFollowButton btn rounded Button hasText gridItem Module ajax notNavigatable ui-FollowButton")
                                {
                                    if (!ListAllFollowers.Contains(strUser)) ListAllFollowers.Add(strUser);
                                    element1.click();
                                    iHaveFollowed++;
                                }
                            }
                        }
                    }
                    catch
                    {
                    }
                }
            }
            ListFollowersEnd = PreListFollowers.Count == listFollowers.Count;
            PreListFollowers = listFollowers;
            if (iHaveFollowed == 0) noFollower++;
            else noFollower = 0;
            if (noFollower > 5) ListFollowersEnd = true;
            timerAutoFollow.Interval = 10000 + 10000 * iHaveFollowed;
            AutoScroll();
            return iHaveFollowed > 0;
        }

        private int iAutoScroll = 1200;
        private void AutoScroll()
        {
            HtmlDocument htmlDocument = this.webBrowser2.Document;
            htmlDocument.Window.ScrollTo(0, iAutoScroll);
            iAutoScroll = iAutoScroll + 1200;
        }

        //private List<string> listUser = new List<string>();
        private bool AutoNextUsersFollowerPage()
        {
            if (iListAllFollowers >= ListAllFollowers.Count) return false;
            webBrowser2.Url = new Uri("http://www.pinterest.com" + ListAllFollowers[iListAllFollowers++] + "followers/");
            return true;
            //IHTMLWindow2 win = (IHTMLWindow2)webBrowser2.Document.Window.DomWindow;
            //foreach (IHTMLElement element in win.document.all)
            //{
            //    if (element.className == "userWrapper")
            //    {
            //        try
            //        {
            //            var strFollowers = element.innerHTML.Substring(element.innerHTML.IndexOf("Pins") + 4, element.innerHTML.IndexOf("Followers") - element.innerHTML.IndexOf("Pins") - 4);
            //            int iFollowers = Convert.ToInt32(strFollowers.Replace(" ", "").Replace("\n", "").Replace("•", "").Replace(",", ""));
            //            if (iFollowers > 1000)
            //            {
            //                var strUser = element.outerHTML.Substring(element.outerHTML.IndexOf("<a class=\"userWrapper\" href=\"") + 29, element.outerHTML.IndexOf("\" data-element-type=\"64\">") - element.outerHTML.IndexOf("<a class=\"userWrapper\" href=\"") - 29);
            //                if (listUser.Contains(strUser))continue;
            //                listUser.Add(strUser);
            //                webBrowser2.Url = new Uri("http://www.pinterest.com" + strUser + "followers/");
            //                return true;
            //            }
            //        }
            //        catch
            //        {
            //        }
            //    }
            //}
            //return false;
        }
        #endregion

    }
}
